package com.shr.lease.web.admin.service.impl;

import com.shr.lease.common.constant.RedisConstant;
import com.shr.lease.web.admin.service.LoginService;
import com.shr.lease.web.admin.vo.login.CaptchaVo;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.ChineseCaptcha;
import com.wf.captcha.SpecCaptcha;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public CaptchaVo getCaptcha() {

        int choose = new Random().nextInt(3) + 1;

        String code;
        String image;

        if (choose == 1) {
            //字符数字验证
            SpecCaptcha captcha = new SpecCaptcha(130, 48, 4);
            captcha.setCharType(SpecCaptcha.TYPE_DEFAULT);
            code = captcha.text().toLowerCase();
            image = captcha.toBase64();
        } else if (choose == 2) {
            //算术验证
            ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48, 3);
            captcha.getArithmeticString();
            code = captcha.text();
            image = captcha.toBase64();
        } else {
            //中文验证
            ChineseCaptcha captcha = new ChineseCaptcha(130, 48, 4);
            code = captcha.text();
            image = captcha.toBase64();
        }
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID();
        stringRedisTemplate.opsForValue().set(key,code,RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC,TimeUnit.SECONDS);
        return CaptchaVo.builder()
                .image(image)
                .key(key)
                .build();
    }
}
